import { constantRoute, asnycRoute, anyRoute } from '@/router/routes.ts'
import router from '@/router/index.ts'
//@ts-expect-error
import cloneDeep from 'lodash/cloneDeep'
import { ref } from 'vue'
import useUserStore from '@/store/modules/user'
import { reqGetUserByUserId } from '@/api/user/userInfo'

export async function getPermissionByUserId(
	userId: string
): Promise<any> {
	const res = await reqGetUserByUserId(userId)
	const role = res?.permissionName
	return role
}

const routes = ref<string[]>([])
const SuperRoutes = [
	'manage',
	'manageUser',
	'quiz',
	'quizIndex',
	'welcome',
	'quizManage',
	'quizHistory',
  'myQuizHistory'
]
const vipRoutes = ['quiz', 'quizIndex', 'welcome']
const normalRoutes = [
	'quiz',
	'quizIndex',
	'welcome',
  'myQuizHistory',
  'quiz'
]

const useStore = useUserStore()

async function getRoutes() {
	const role = await getPermissionByUserId(useStore.userId)
  console.log('role:', role)
	if (role != undefined) {
		if (role === '管理员') {
			console.log('SuperRoutes:', SuperRoutes)
			return SuperRoutes
		} else if (role === 'VIP') {
			console.log('vipRoutes:', vipRoutes)
			return vipRoutes
		} else {
			console.log('normalRoutes:', normalRoutes)
			return normalRoutes
		}
	} else {
		console.log('不匹配', normalRoutes)
		return normalRoutes
	}
}

// const routes=ref<string[]>(['manage','manageUser','quiz','quizIndex','welcome','quizManage','quizHistory'])
routes.value = await getRoutes()
function filterAsyncRoute(asnycRoute: any, routes: any) {
	return asnycRoute.filter((item: any) => {
		if (routes.value.includes(item.name)) {
			if (item.children && item.children.length > 0) {
				item.children = filterAsyncRoute(item.children, routes)
			}
			return true
		}
	})
}
export function getMenuRoutes() {
	const userAsyncRoute = filterAsyncRoute(cloneDeep(asnycRoute), routes)
	//菜单需要的数据整理完毕
	const menuRoutes = [...constantRoute, ...userAsyncRoute, anyRoute]
	//目前路由器管理的只有常量路由:用户计算完毕异步路由、任意路由动态追加
	;[...userAsyncRoute, anyRoute].forEach((route: any) => {
		router.addRoute(route)
	})

	return menuRoutes
}
